/*
 * hkh-project
 * leafteamwork.blogspot.com
 * Tool: Netbeans 6.7.1 - SQL Server 2005
 */
package vn.com.hkh.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.com.hkh.dto.UserDTO;
import vn.com.hkh.service.UserService;
import vn.com.hkh.util.DatabaseUtil;

/**
 *
 * @author leaf
 */
public class UserAction extends HttpServlet {

    private UserService us = null;

    @Override
    public void init() throws ServletException {
        super.init();
        us = new UserService();
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        PrintWriter out = response.getWriter();

        String _forward = "";
        String _message = "";

        try {
            if (request.getSession().getAttribute("login") == null) {
                _message = "Please login!";
                //forward = "/view/login.jsp";
                request.setAttribute("message", _message);
                RequestDispatcher rd = request.getRequestDispatcher("/LoginAction");
                rd.forward(request, response);
            } else {
                // T01. CLIENT PROCESS
                String _action = request.getParameter("act");
                _action = (_action == null) ? "list" : _action;
                // T02. CRUD PROCESS
                if (_action.equalsIgnoreCase("add")) {
                    UserDTO _userDTO = new UserDTO();
                    //TODO: *** Add User task
                    //request from useradd
                    _userDTO.setUsername(request.getParameter("username"));
                    _userDTO.setPassword(request.getParameter("password"));
                    _userDTO.setAlias(request.getParameter("alias"));
                    _userDTO.setRoleID(request.getParameter("role"));
                    _userDTO.setAccountID(request.getParameter("username"));
                    _userDTO.setStatus(Integer.parseInt(request.getParameter("status")));
                    _userDTO.setWhen(request.getParameter("when"));

                    UserDTO _result = us.create(_userDTO);
                    if (_result == null) {
                        _message = "Add Error!";
                        request.setAttribute("user", _userDTO);
                        _action = "addform";
                    } else {
                        _message = "Add Successful!";
                        _action = "list";
                    }
                } else if (_action.equalsIgnoreCase("edit")) {
                    UserDTO _userDTO = new UserDTO();
                    //TODO: *** Edit User task
                    //request from useredit
                    _userDTO.setUsername(request.getParameter("username"));
                    _userDTO.setPassword(request.getParameter("password"));
                    _userDTO.setAlias(request.getParameter("alias"));
                    _userDTO.setRoleID(request.getParameter("role"));
                    _userDTO.setAccountID(request.getParameter("username"));
                    _userDTO.setStatus(Integer.parseInt(request.getParameter("status")));
                    _userDTO.setWhen(DatabaseUtil.getYMD(request.getParameter("when")));

                    UserDTO _result = us.store(_userDTO);
                    if (_result == null) {
                        _message = "Update Error!";
                        request.setAttribute("user", _userDTO);
                        _action = "editform";
                    } else {
                        _message = "Update Successful!";
                        _action = "list";
                    }
                } else if (_action.equalsIgnoreCase("del")) {
                    String primaryKey = request.getParameter("pk");
                    boolean result = us.remove(primaryKey);
                    _message = result ? "Delete Successful!" : "Delete Error!";
                    _action = "list";
                } else if (_action.equalsIgnoreCase("cancel")) {
                    _message = null;
                    _action = "list";
                } else if (_action.equalsIgnoreCase("change")) {
                    String _newPassword = request.getParameter("newPassword");
                    UserDTO _userDTO = (UserDTO) request.getSession().getAttribute("login");
                    String _oldPassword = request.getParameter("oldPassword");
                    if (_oldPassword.equalsIgnoreCase(_userDTO.getPassword())) {
                        boolean result = us.store(_userDTO.getUsername(), _newPassword);
                        _message = (result == true) ? "Change Password Successful!" : "Change Password Error!";
                        _action = "list";
                    } else {
                        _message = "old password incorrect !";
                        _action = "changeform";
                    }
                }

                // T03. FORWARD PROCESS
                if (_action.equalsIgnoreCase("list")) {
                    Collection<UserDTO> _userDTO = us.findUsers();
                    request.setAttribute("users", _userDTO);
                    _forward = (_userDTO == null) ? "" : "/view/userlist.jsp";
                } else if (_action.equalsIgnoreCase("addform")) {

                    _forward = "/view/useradd.jsp";
                } else if (_action.equalsIgnoreCase("editform")) {
                    UserDTO _userDTO = (UserDTO) request.getAttribute("user");
                    if (_userDTO == null) {
                        String _username = request.getParameter("pk");
                        _userDTO = us.findByPrimaryKey(_username);
                        request.setAttribute("user", _userDTO);
                    }
                    _forward = (_userDTO == null) ? "" : "/view/useredit.jsp";
                } else if (_action.equalsIgnoreCase("changeform")) {
                    _forward = "/view/passwordchange.jsp";
                } else if (_action.equalsIgnoreCase("logout")) {
                    _message = null;
                    request.getSession().removeAttribute("login");
                    _forward = "/view/login.jsp";
                } else {
                    _forward = "/view/adminview.jsp";
                }
                //T04. LOOKUP & FORWARD TO VIEW

                request.setAttribute("from", "useraction");
                request.setAttribute("message", _message);
                request.setAttribute("forward", _forward);
                RequestDispatcher rd = request.getRequestDispatcher("/view/adminlayout.jsp");
                rd.forward(request, response);
            }


        } finally {
            out.close();
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    @Override
    public void destroy() {
        super.destroy();
        us =
                null;
    }
}
